<?php

namespace Common\Model;
use Think\Model;


abstract class XuecheModel extends \Think\Model {

    const FILE = 'File';
    const MEMCACHE = 'Memcache';
    const REDIS = 'Redis';

    public function __construct($name='',$tablePrefix='',$connection='') {
        parent::__construct($name, $tablePrefix, $connection);
        // 数据表前缀
        $this->tablePrefix = C('DB_PREFIX');
        // 数据库名称
        $this->dbName = C('DB_NAME');
        // 模型名称
        $this->dbName = '';
        //缓存初始化
        if($this->_useCache){
            S(array('type'=>$this->_useCacheType,'expire'=>$this->_cacheTime));
        }
    }


    /**
     * 是否使用缓存
     * @var bool
     * @access protected
     */
    protected $_useCache = False;

    /**
     *
     * 使用哪个缓存，(Apachenote、Apc、Db、Eaccelerator、File、Memcache、Redis、Shmop、Sqlite、Wincache和Xcache).
     * @var string
     */
    protected $_useCacheType = 'File';

    /**
     *
     * 缓存时间
     * @var second
     */
    protected $_cacheTime = 86400;

    /**
     *
     * 缓存对象
     * @var object
     */
    private $_cache = NULL;


    /**
     * 自动验证
     */
    protected $autoValidate = false;

    /**
     *
     * 临时数据
     * @var unknown_type
     */
    private $_tmpFields = array();

    /**
     *
     * 是否清除缓存
     * @var bool
     */
    protected $_clearCache = FALSE;
    //特殊数据
    protected $_group = '';





    /**
     * 获取数据列表
     * @param string $where
     * @param type $order
     * @param type $offset
     * @param type $limit
     * @param type $fields
     * @return type
     */
    public function getList($where = '', $order = '', $offset = 0, $limit = 18,$fields = '',$total = true){
        $cacheName = md5($where.$order.$offset.$fields);
        $cacheValue = S($cacheName);
        if($this->_useCache && $cacheValue){
            return $cacheValue;
        }
        if(empty($where)){
            $where = '1 = 1';
        }
        if(empty($order)){
            $order = "`{$this->pk}` DESC";
        }
        if(empty($fields)){
            $fields = implode(',', $this->fields);
            $fields = rtrim($filed, ',');
        }

        $data = $this->where($where)->order($order)->limit($offset,$limit)->field($fields)->select();

        if ($total) {
            $count = $this->getCount($where);
            $data = array('total'=>$count,'lists'=>$data);
        }else{
             $data = array('lists'=>$data);
        }
        if($this->_useCache){
            S($cacheName,$data);
        }
        return $data;
    }

    /**
     * 数据库枚举字段的 跟新方法
     * @param type $id
     * @param type $value
     * @param type $field
     * @return boolean
     */
    public function openClose($id,$value = 0,$field = 'disabled'){
        if(in_array($field,$this->fields) && $id > 0){
            $where = "`$this->pk` = '{$id}'";
            if(!empty($value)){
                return $this->where($where)->save(array($field=>$value));;
            }
           $value = $this->where($where)->field($field)->find();
           if($value[$field] == '1'){
               return $this->where($where)->save(array($field=>'2'));
           }else{
               return $this->where($where)->save(array($field=>'1'));
           }
        }
        return FALSE;
    }

    //根据主键修改某个字段的值
    public function updateField($field='',$value='',$id=0){
        $field = empty($field)?I('request.field'):$field;
        $value = empty($value)?I('request.value'):$value;
        $id = empty($id)?I('request.id'):$id;
        //p($id);p($value);p($field);
        if(in_array($field, $this->fields) && $id > 0 && $value){
            $d = array($field=>$value);
            \Think\Log::write(var_export($d,1));
            return $this->where("`$this->pk` = '{$id}'")->save($d);
        }

    }

    /**
     * 跟新数据
     * @param type $id
     * @param type $data
     */
    public function updateById($id,$data){
        if(!is_array($data) || empty($id)){
            return FALSE;
        }
        $field = array_keys($data);
        $value = array_values($data);
        foreach($field as $v){
            if(!in_array($v, $this->fields)){
                return FALSE;
            }
        }
        if(!$this->Validate($data)){
            return FALSE;
        }
        return $this->where("`$this->pk` = '{$id}'")->save($data);
    }





    /**
     * 根据主键ID获取一条数据
     * @param type $id
     * @return boolean
     */
    public function getOneList($id,$field = ''){
        if($id > 0){
            return $this->where("`{$this->pk}` = '{$id}'")->field($field)->find();
        }
    }

        /**
     * 获取总数
     * @param type $where
     * @return type
     */
    public function getCount($where){
        return $this->where($where)->count($this->pk);
    }


    /**
     *
     * 保存信息,修改信息
     * @param $data
     * @param $pks		能判断唯一的键组
     * @param bool $autoValidate 是否自动验证
     */
    public function saveData($data, $pks = array()) {
        if ($this->autoValidate) {
            if ($this->Validate($data) == FALSE) {
                return FALSE;
            }
        }
        $thisPk = $this->getPk();
        if ($pks && is_array($pks)) {
            foreach ($pks as $k=>$v) {
                if ($v > 0) {
                    $where .= "AND `{$k}` = '{$v}'";
                }
            }
            $where = trim($where,'AND');
        } else if ($data[$thisPk]) {
            $where = '`' . $thisPk . '` = \'' . $data[$thisPk] . '\'';
        }
        if(empty($data[$thisPk])){
            unset($data[$thisPk]);
        }

        if (empty($where)) {
            return $this->add($data);
        } else {
            if ($this->getCount($where) > 0) {
                    unset($data[$thisPk]);
                    return $this->where($where)->save($data);
            } else {
                return $this->add($data);
            }
        }
    }






    /**
     *
     * 设置缓存时间
     * @param int $second
     */
    public function SetCacheTime($second) {
        $this->EnabledCache();
        $this->_cacheTime = $second;
    }

    /**
     *
     * 启动缓存
     */
    public function EnabledCache() {
        $this->_useCache = TRUE;
    }

    /**
     *
     * 禁用缓存
     */
    public function DisEnabledCache() {
        $this->_useCache = FALSE;
    }

    /**
     *
     * 设置缓存类型
     *
     * @param $type 缓存类型
     */
    public function SetCacheType($type = XibuModel::FILE) {
        $this->_useCacheType = $type;
    }

    /**
     *
     * 清除缓存
     */
    public function ClearCache() {
        $this->_clearCache = TRUE;
    }

    /**
     *
     * 重设fields
     */
    public function ResetFields() {
        $this->fields = $this->_tmpFields;
    }

    /**
     *
     * 数据验证
     */
    abstract function Validate($data);
}
